// import Nevow.Athena
// import Divmod.Runtime

Meercat.Storage.List = Nevow.Athena.Widget.subclass('Meercat.Storage.List');
Meercat.Storage.Add = Nevow.Athena.Widget.subclass('Meercat.Storage.Add');

Meercat.Storage.List.methods(
function loaded(self) {
    self.refresh();
},
function refresh(self) {
    d = self.callRemote('getStorageList');
    d.addCallback(function (result) {
        var ul = jQuery('#' + escapeId(self.node.id) + ' > ul.StorageList');
        ul.empty();
        
        for (i = 0; i < result.length; i++) {
            ul.append('<li>' + result[i] + '<a href="#" ' + 
                'onclick="Nevow.Athena.Widget.get(this).removeStorage(\'' + 
                result[i] + '\');">[x]</a></li>');
        }
    });
    
    return d;
},
function removeStorage(self, name) {
    d = self.callRemote('deleteStorage', name);
    d.addCallback(function (result) {
        self.refresh();
    });
    
    d.addErrback(function (failure) {
        alert('Error removing harvester: ' + failure);
    });
},
function addStorageElement(self) {
	var d = self.callRemote('getAddStorageElement');
	
	d.addCallback(function (le) {
		var d2 = self.addChildWidgetFromWidgetInfo(le);
		d2.addCallback(function (widget) {
			jQuery('#main-content').append(widget.node);
		});
	});
	
	d.addErrback(function (failure) {
	    alert('Error creating an add storage form');
	});
});

Meercat.Storage.Add.methods(
function addStorage(self) {
    var d = self.callRemote('createStorage',
                            self.firstNodeByAttribute('name','name').value,
                            self.firstNodeByAttribute('name','schema').value);
    
    d.addCallback(function (result) {
        self.widgetParent.refresh();
        self.remove();
    });
    
    d.addErrback(function (failure) {
        alert('Error adding the harvester: ' + failure);
    });
},
function remove(self) {
    var d = self.detach();
    d.addCallback(function (result) {
        jQuery('#' + escapeId(self.node.id)).remove();
    });
    
    d.addErrback(function (failure) {
        alert('Error detaching the add harvester form: ' + failure);
    });
});
